package com.gitee.huanminabc.fastboot.event;

import com.gitee.huanminabc.jcommon.multithreading.executor.ThreadFactoryUtil;
import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.exception.ApplicationListenerNotFoundException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
@Slf4j
public class AppEventPublisher {
    public static void publishEvent(AppEvent event) {
        publishEvent(event, false, null);
    }

    public static void publishEventAsync(AppEvent event) {
        publishEvent(event, true, event.getEventName());
    }

    public static void publishEventAsync(AppEvent event, String threadName) {
        publishEvent(event, true, threadName);
    }

    public static void publishEvent(AppEvent event, boolean async, String threadName) {
        List<AppListener<AppEvent>> appListeners = AppContext.appListenerMap.get(event.getClass());
        if (appListeners == null) {
            throw new ApplicationListenerNotFoundException("没有找到事件监听器,事件类型:" + event.getClass().getName());
        }
        if (async) {
            for (AppListener<AppEvent> appListener : appListeners) {
                ThreadFactoryUtil.getExecutor(threadName).execute(() -> {
                    try {
                        appListener.onApplicationEvent(event);
                    } catch (Exception e) {
                        log.error("事件监听器执行异常,事件类型:{},监听器类型:{}", event.getClass().getName(), appListener.getClass().getName(), e);
                    }
                });
            }
        } else {
            for (AppListener<AppEvent> appListener : appListeners) {
                appListener.onApplicationEvent(event);
            }
        }
    }
}
